﻿@using Xms.Flow.Abstractions;

@model Xms.Web.Models.BusinessProcessModel
@{
    Layout = null;
}
@{
    var entityLastStage = Model.Stages.FindLast(n => n.EntityId == Model.EntityId);
    var currentStage = Model.Stages.Find(n => n.ProcessStageId == Model.CurrentStageId) ?? Model.Stages.First();
}

<style>
    .icon-process-flag {
        position: absolute;
        top: -18px;
        left: 10px;
        width: 26px;
        height: 26px;
        background: url('/content/images/process-control-global-active-flag.png') no-repeat;
        z-index: 3;
    }

    .icon-process-r1,
    .icon-process-r1-hv {
        width: 11px;
        height: 21px;
        background: url("/content/images/process-control-arrows.png") no-repeat;
    }

    .icon-process-r1 {
        background-position: 0 0;
    }

    .icon-process-r1-hv {
        background-position: -42px 0;
    }

    .icon-process-r2 {
        background-position: -21px 0;
    }

    .icon-process-r2-hv {
        background-position: -63px 0;
    }

    .icon-advance-arrow {
        width: 15px;
        height: 15px;
        background: url('/content/images/forward-icon.png') no-repeat;
    }

    .icon-back-arrow {
        width: 15px;
        height: 15px;
        background: url('/content/images/back-icon.png') no-repeat;
    }

    .nav-tabs > li > a {
        margin-right: 0;
    }

    .c-hide {
        display: none;
    }

    .v-hide {
        visibility: hidden;
    }

    .v-show {
        visibility: visible;
    }

    .fl {
        float: left;
    }

    .fr {
        float: right;
    }

    .menter {
        width: 100%;
        height: 24px;
        border: 1px dashed #ccc;
        background: #f3f1f1;
    }

    .icon-arrow-forward {
        position: absolute;
        right: 0px;
        top: 0px;
        z-index: 10;
        font-size: 0;
        line-height: 0;
        border-width: 13px;
        border-color: #777;
        border-right-width: 0;
        border-style: dashed;
        border-left-style: solid;
        border-top-color: transparent;
        border-bottom-color: transparent;
    }

    .arrow-white {
        font-size: 0;
        line-height: 0;
        border-width: 13px;
        border-color: #fff;
        border-right-width: 0;
        border-style: dashed;
        border-left-style: solid;
        border-top-color: transparent;
        border-bottom-color: transparent;
        position: absolute;
        left: 0px;
        top: 0px;
        z-index: 2;
    }

    .process {
        width: 100%;
        margin: 0 auto;
        margin-top: 20px;
        padding: 0;
    }

        .process i {
            display: inline-block;
        }

        .process .wMax {
            width: 100%;
        }

        .process .clr:after {
            display: table;
            content: " ";
            clear: both;
        }

        .process .hv:hover {
            cursor: pointer;
        }

        .process .nav-tabs {
            border-bottom: none;
            position: relative;
            display: table;
            width: 100%;
        }

            .process .nav-tabs li {
                margin-left: -3px;
                display: table-cell;
                padding-right: 13px;
                white-space: nowrap;
                float: none;
            }

                .process .nav-tabs li:first-child {
                    margin-left: 0px;
                }

                .process .nav-tabs li:last-child {
                    padding-right: 0px;
                }

                .process .nav-tabs li.stage-item-prev {
                }

                .process .nav-tabs li.stage-item-next {
                }

                .process .nav-tabs li.stage-item-prev-next {
                }

                .process .nav-tabs li.stage-item a {
                    padding-left: 40px;
                    line-height: 20px;
                }

            .process .nav-tabs > li > a {
                border-radius: 0;
                cursor: pointer;
            }

        .process .nav > li > a {
            padding: 3px 15px;
        }

        .process .nav-tabs > li > a,
        .process .nav-tabs > li > a:hover {
            color: #fff;
            background: #777;
            border: none;
        }

        .process .nav
        .process .nav-tabs > li.active > a,
        .process .nav-tabs > li > a {
            background: #777;
        }

        .process .nav > li > a:focus,
        .process .nav > li > a:hover {
            background: #777;
        }

        .process .nav-tabs > li.active .icon-arrow-forward {
            border-color: #cd9835;
            border-top-color: transparent;
            border-bottom-color: transparent;
        }

        .process .nav-tabs > li.active > a,
        .process .nav-tabs > li.active > a:focus,
        .process .nav-tabs > li.active > a:hover {
            background: #cd9835;
            color: #fff;
            line-height: 20px;
            border: none;
        }

        .process .tab-content-wrap {
            margin-top: 1px;
            border-top: 2px solid #cd9835;
            border-bottom: 2px solid #cd9835;
        }

            .process .tab-content-wrap.slide-up {
                border-top-width: 1px;
                border-bottom-width: 1px;
            }

        .process .nav-tabs .icon-process-flag {
            display: none;
        }

        .process .nav-tabs li.flag .icon-process-flag {
            display: inline-block;
        }

        .process .detail-table {
            min-height: 100px;
            padding-top: 14px;
            padding-bottom: 24px;
            font-size: 12px;
            font-family: "Microsoft YaHei", "Helvetica Neue", Tahoma, "Microsoft Sans Serif", Verdana, sans-serif;
        }

        .process .nav-tabs .icon-back-arrow,
        .process .next-stage .icon-advance-arrow {
            position: relative;
            top: 3px;
        }

        .process .nav-tabs .prev-stage {
            width: 20px;
            padding: 0;
            padding-right: 5px;
        }

            .process .nav-tabs .prev-stage > a {
                padding-left: 3px;
            }

            .process .nav-tabs .prev-stage.act > a,
            .process .nav-tabs .next-stage.act > a {
                background: #cd9835;
                cursor: pointer;
            }

    .collapsible-view {
        position: relative;
    }

        .collapsible-view .info-wrapper .icon-info {
            width: 8px;
            height: 8px;
            background: url('/content/images/info_icon.png') no-repeat;
        }

        .collapsible-view .container-button .icon-collapsible {
            width: 8px;
            height: 6px;
            background: url('/content/images/Collapse_Icon.png') no-repeat;
            cursor: pointer;
        }

        .collapsible-view .container-left {
            position: absolute;
            right: 0;
            top: -22px;
        }

        .collapsible-view .container-button {
            width: 24px;
            height: 22px;
            background-color: #c07e03;
            opacity: 0.8;
            text-align: center;
        }

    .container-left .info-wrapper {
        width: 14px;
        height: 22px;
        background-color: #c07e03;
        opacity: 0.8;
        text-align: center;
    }

    .container-left .proces-text {
        padding: 1px;
        color: #fff;
        background: #c07e03;
        opacity: 0.8;
    }

    .next-stage {
        position: relative;
    }

    .stage-new-item {
        position: absolute;
        width: 100%;
        top: 26px;
        z-index: 11;
        right: 0;
        background: #fff;
        border: 2px solid #cd9835;
    }

    .stage-new-header {
        border-bottom: 2px solid #cd9835;
        padding: 5px;
    }

    .stage-new-content {
        min-height: 40px;
        max-height: 200px;
        overflow-y: auto;
        border-bottom: 2px solid #cd9835;
        padding: 5px;
    }

    .stage-new-footer {
        font-style: normal;
        padding: 5px;
    }

    .stage-new-content ul {
        padding: 0;
        margin: 0;
    }

    #stage-list > li {
        display: block;
        padding: 2px;
        cursor: pointer;
        margin: 2px 5px;
    }

    em.stage-list-count {
        font-style: normal;
    }

    li.success-stage:before {
        content: '\e013';
        display: block;
        font-family: 'Glyphicons Halflings';
        font-style: normal;
        color: #fff;
        position: absolute;
        left: 19px;
        top: 5px;
        z-index: 1;
    }

    .bpattr-item-panel {
        margin-bottom: 5px;
    }

    .bpattr-item-label {
        white-space: nowrap;
    }
</style>

<div class="process container-fluid" data-count="@Model.Stages.Count" data-workflowid="@Model.BusinessFlow.WorkFlowId">
    <ul class="nav nav-tabs" role="tablist" id="businessprocess-lists">
        @{
            string isEdited = "true";
        }
        @foreach (var stage in Model.Stages)
        {
            Xms.Schema.Domain.RelationShip rs = null;
            Xms.Core.Data.Entity relatedRecord = null;
            if (stage.RelationshipName.IsNotEmpty())
            {
                rs = Model.RelationShips.Find(n => n.Name.IsCaseInsensitiveEqual(stage.RelationshipName));
            }
            if (Model.BusinessFlowInstance != null)
            {
                relatedRecord = Model.RelatedRecords.ContainsKey(stage.EntityId.ToString()) ? Model.RelatedRecords[stage.EntityId.ToString()] as Xms.Core.Data.Entity : null;
            }
            else if (stage.StageOrder == 1)
            {
                relatedRecord = Model.Data;
            }
            string stageClass = (stage.ProcessStageId == Model.CurrentStageId ? " flag stage-item-next" : "");
            if (stage.EntityId == Model.EntityId)
            {
                if (stage.ProcessStageId == Model.CurrentStageId)
                {
                    stageClass += " active";
                }
                else if (currentStage.EntityId != Model.EntityId && stage.ProcessStageId == entityLastStage.ProcessStageId)
                {
                    stageClass += " active";
                }
            }
            <li role="presentation" class="stage-item@(stageClass)" data-isedited="@isEdited" data-entityname="@(rs!=null?rs.ReferencingEntityName:"")" data-referencingentitylocalizedname="@(rs!=null?rs.ReferencingEntityLocalizedName:"")" data-relateattributename="@(rs!=null?rs.ReferencedAttributeName:"")" data-stageid="@stage.ProcessStageId" data-entityid="@stage.EntityId" data-relationshipname="@stage.RelationshipName" data-recordid="@(relatedRecord != null ? relatedRecord.GetIdValue().ToString() : "")">
                <i class="icon-process-flag"></i>
                @if (stage.StageOrder > 1)
                {
                    <span class="arrow-white"></span>
                }
                <a href="#tab@(stage.StageOrder)" aria-controls="tab@(stage.StageOrder)" role="tab" data-toggle="tab">@stage.Name</a>
                @if (stage.StageOrder < Model.Stages.Count)
                {
                    <span class="icon-arrow-forward"></span>
                }
            </li>
            if (stage.ProcessStageId == Model.CurrentStageId)
            {
                isEdited = "";
            }
        }
        @if (Model.Stages.First().ProcessStageId != Model.CurrentStageId)
        {
            <li class="prev-stage">
                <a href="javascript:void(0)" @(!currentStage.EntityId.Equals(Model.EntityId) ? " disabled" : "")>
                    <i class="icon-back-arrow"></i>
                </a>
            </li>
        }
        <li class="" id="nextStageBtn">
            @if (Model.Stages.Last().ProcessStageId != Model.CurrentStageId)
            {
                <a href="javascript:void(0)" class="next-stage" @(!currentStage.EntityId.Equals(Model.EntityId) ? " disabled" : "")>
                    <i class="icon-advance-arrow"></i>下一阶段
                </a>
            }
            <div class="stage-new-item" style="display:none;">
                <div class="stage-new-header">
                    选择记录
                </div>
                <div class="stage-new-content">
                    <ul id="stage-list">
                        <li></li>
                    </ul>
                </div>
                <div class="stage-new-footer clearfix">
                    <span class=""><em class="stage-list-count">0</em>可用</span>
                    <a class="pull-right" id="creatNewStageRec">新建</a>
                </div>
            </div>
        </li>
    </ul>

    <div class="tab-content-wrap">
        <div class="tab-content">
            @foreach (var stage in Model.Stages)
            {
                var steps = Model.Steps[stage.ProcessStageId.ToString()] as List<ProcessStep>;
                var isdisabled = stage.ProcessStageId == Model.CurrentStageId ? "" : "disabled";
                Xms.Core.Data.Entity relatedRecord = null;
                Xms.Schema.Domain.RelationShip rs = null;
                if (Model.BusinessFlowInstance != null && stage.RelationshipName.IsNotEmpty())
                {
                    rs = Model.RelationShips.Find(n => n.Name.IsCaseInsensitiveEqual(stage.RelationshipName));
                    relatedRecord = Model.RelatedRecords.ContainsKey(stage.EntityId.ToString()) ? Model.RelatedRecords[stage.EntityId.ToString()] as Xms.Core.Data.Entity : null;
                }
                string stageClass = "";// (stage.ProcessStageId == Model.CurrentStageId && stage.EntityId.Equals(Model.EntityId) ? " active" : "");
                if (stage.EntityId == Model.EntityId)
                {
                    if (stage.ProcessStageId == Model.CurrentStageId)
                    {
                        stageClass += " active";
                    }
                    else if (currentStage.EntityId != Model.EntityId && stage.ProcessStageId == entityLastStage.ProcessStageId)
                    {
                        stageClass += " active";
                    }
                }
                <div role="tabpanel" class="tab-pane@(stageClass)" id="tab@(stage.StageOrder)">
                    <div class="detail-table clearfix" data-count="@steps.Count">
                        @foreach (var step in steps)
                        {
                            var attr = Model.Attributes.Find(n => n.Name.IsCaseInsensitiveEqual(step.AttributeName) && n.EntityId == stage.EntityId);
                            if (attr == null)
                            {
                                continue;
                            }
                            step.AttributeName = step.AttributeName.ToLower();
                            attr.Name = attr.Name.ToLower();
                            <div class="col-sm-4 bpattr-item-panel">
                                <label class="col-sm-4 bpattr-item-label" for="bp_@(step.AttributeName.ToLower())">@step.DisplayName@Html.Raw(step.IsRequired ? "<span style='color:red;font-weight:bolder;'>*</span>" : "")</label>
                                <div class="col-sm-8">
                                    @if (stage.EntityId.Equals(Model.EntityId))
                                    {
                                        if (attr.AttributeTypeName == "lookup" || attr.AttributeTypeName == "owner" || attr.AttributeTypeName == "customer" || attr.AttributeTypeName == "primarykey")
                                        {
                                            var onlylabel = isdisabled == "disabled" ? "data-onlylabel='true' " : "";
                                            <input type="text" class="form-control input-sm @attr.AttributeTypeName lookup" name="bp_@(step.AttributeName.ToLower())_text" id="bp_@(step.AttributeName.ToLower())_text" data-attributeid="@attr.AttributeId" data-attributename="@(step.AttributeName.ToLower())" @(isdisabled) data-attributetype="@attr.AttributeTypeName" data-type="guid" value="" data-lookup="@attr.ReferencedEntityId" data-localizedname="@attr.LocalizedName">
                                            <input type="hidden" class="haslookup bp_input" name="bp_@(step.AttributeName.ToLower())" id="bp_@(step.AttributeName.ToLower())" disabled="@(isdisabled)" data-attributeid="@attr.AttributeId" data-type="guid" value="" data-lookup="@attr.ReferencedEntityId" data-localizedname="@attr.LocalizedName">
                                        }
                                        else if (attr.DataFormat == "textarea")
                                        {
                                            <textarea class="form-control bp_input @attr.AttributeTypeName input-sm@(step.IsRequired ? " required" : "")" name="bp_@step.AttributeName.ToLower()" @(isdisabled) data-optionsetid="@attr.OptionSetId" data-attributename="@step.AttributeName.ToLower()" data-format="@attr.DataFormat" id="bp_@step.AttributeName.ToLower()" data-attributeid="@attr.AttributeId" data-attributetype="@attr.AttributeTypeName" />
                                        }
                                        else if (attr.DataFormat == "picklist")
                                        {
                                            <input type="text" class="form-control @attr.AttributeTypeName bp_input input-sm@(step.IsRequired ? " required" : "")" name="bp_@step.AttributeName.ToLower()" @(isdisabled) data-optionsetid="@attr.OptionSetId" data-attributename="@step.AttributeName.ToLower()" data-format="@attr.DataFormat" id="@step.AttributeName.ToLower()" data-attributeid="@attr.AttributeId" data-attributetype="@attr.AttributeTypeName" />
                                        }
                                        else if (attr.AttributeTypeName == "datetime")
                                        {
                                            <div class="input-group">
                                                <span class="input-group-addon"><em class="glyphicon glyphicon-calendar"></em></span>
                                                <input type="text" class="form-control bp_input @attr.AttributeTypeName input-sm@(step.IsRequired ? " required" : "")" name="bp_@step.AttributeName.ToLower()" @(isdisabled) data-optionsetid="@attr.OptionSetId" data-attributename="@step.AttributeName.ToLower()" data-format="@attr.DataFormat" id="bp_@step.AttributeName.ToLower()" data-attributeid="@attr.AttributeId" data-attributetype="@attr.AttributeTypeName" />
                                            </div>
                                        }
                                        else
                                        {
                                            <input type="text" class="form-control bp_input @attr.AttributeTypeName input-sm@(step.IsRequired ? " required" : "")" name="bp_@step.AttributeName.ToLower()" @(isdisabled) data-optionsetid="@attr.OptionSetId" data-attributename="@step.AttributeName.ToLower()" data-format="@attr.DataFormat" id="bp_@step.AttributeName.ToLower()" data-attributeid="@attr.AttributeId" data-attributetype="@attr.AttributeTypeName" />
                                        }
                                    }
                                    else
                                    {
                                        <span>@(relatedRecord.NotEmpty() ? relatedRecord[attr.Name] : "")</span>
                                    }
                                </div>
                            </div>
                        }
                    </div>
                </div>
            }
            <div class="collapsible-view">
                <div class="container-left clr">
                    <div class="container-button fr">
                        <i class="icon-collapsible"></i>
                    </div>
                    <div class="info-wrapper fr">
                        <i class="icon-info"></i>
                    </div>
                    <div class="proces-text fr v-hide" title="@Model.BusinessFlow.Name">
                        @Model.BusinessFlow.Name
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var BusinessProcessModel = {
        WorkFlowId: '@Model.BusinessFlow.WorkFlowId'
        , EntityId: '@Model.EntityId'
        , InstanceId: '@(Model.BusinessFlowInstance != null ? Model.BusinessFlowInstance.BusinessProcessFlowInstanceId.ToString() : "")'
        , setInitIdAndName: function () {
            var formWrap = $("#businessprocess-section");
            var $inputs = formWrap.find('.bp_input');
            $inputs.each(function (key, item) {
                var itemId = $(item).attr("id").replace(/^bp_/, "");
                var creatFromInput = $('[name="' + itemId + '"]', '.xmsformContent');
                // console.log($('[name="' + itemId + '"]', '.xmsformContent'))
                var datatype = $(item).attr('data-attributetype');
                if (creatFromInput.length == 0) {
                    var attrname = itemId.replace(/^bp_/, "");
                    $(item).attr("id", attrname + "_text");
                    $(item).attr("name", attrname);

                    datatype = datatype ? datatype : $(item).prev().attr('data-attributetype');
                    if (datatype == "lookup" || datatype == "customer" || datatype == "owner") {
                        var lookup = $(item).prev();
                        lookup.attr("id", attrname + "_text");
                        lookup.attr("name", attrname + "_text");
                        $(item).attr("id", attrname);
                    }
                    else {
                        if (_record[itemId] && _record[itemId] != "") {
                            $(item).val(_record[itemId])
                        }
                    }
                } else if (creatFromInput.length > 0) {
                    datatype = datatype ? datatype : $(item).prev().attr('data-attributetype');
                    if (datatype == "picklist") {
                        $(item).attr("id", "bp_" + itemId + "_text");
                        $(item).attr("name", "bp_" + itemId);
                    }
                }
            });
        }
        , initFormSetData: function () {
            var formWrap = $("#businessprocess-section");
            var $inputs = formWrap.find('.bp_input');
            console.log('initFormSetData', $inputs);
            var oldrecord = _record;
            BusinessProcessModel.retrieveById(function (res) {
                var _record = res.content;
                if (!_record) {
                    _record = oldrecord;
                }
                $inputs.each(function (key, item) {
                    var source_id = $(item).attr("id");
                    var itemId = $(item).attr("id").replace(/^bp_/, "").replace(/_text$/, "");
                    var $parents = $(item).parents('.bpattr-item-panel:first');
                    var $label = $parents.find('label:first');
                    $label.attr('for',source_id)
                    var creatFromInput = $('[name="' + itemId + '"]', '.xmsformContent');
                    var bussinessInput = $('[name="' + source_id + '"]');
                    var datatype = $(item).attr('data-attributetype');
                    var _format = $(item).attr('data-format');
                    console.log('initFormSetData.item', bussinessInput);
                    console.log(datatype, creatFromInput)
                    if (creatFromInput.length > 0) {
                        bussinessInput.val(_record[itemId]);
                        var lookup = $(item).prev().find('input.lookup ');
                        if (lookup.length > 0) {
                            datatype = datatype ? datatype : $(item).prev().find('input.lookup ').attr('data-attributetype');
                        }
                        if (datatype == 'picklist') {

                            $(item).on('bindinput.complete', function () {
                                var $target = $(item).next();
                                dirtyChecker.bindCheckerEvent([{ key: this.id, value: this.value }]);
                                $target.on('change', function () {
                                    creatFromInput.next().val($(this).val());
                                    creatFromInput.val($(this).val());
                                    creatFromInput.trigger('change');
                                });
                                creatFromInput.next().on('change', function () {
                                    $target.val($(this).val());
                                    $(item).val($(this).val());
                                });
                            })

                        } else if (datatype == "lookup" || datatype == "customer" || datatype == "owner") {
                            var targetLookup = creatFromInput.prev().find('input.lookup');
                            lookup.on('change', function () {
                                targetLookup.val($(this).val());
                                creatFromInput.val($(item).val());
                                // console.log(creatFromInput, targetLookup);
                                creatFromInput.trigger("label.changeLabel");
                                creatFromInput.trigger("extend.changetext");
                                $.fn.xmsSelecteDown.setLookUpState(targetLookup);
                            }).on('lookup.clear', function () {
                                var inputid = targetLookup.attr('id');
                                var valueid = inputid.replace(/_text$/, "");
                                $('#' + inputid).val('').trigger('change');
                                $('#' + valueid).val('').trigger('change');

                                if ($('#' + inputid).siblings(".xms-dropdownLink").length > 0) {
                                    $('#' + inputid).siblings(".xms-dropdownLink").remove();
                                }
                            });
                            targetLookup.on('change', function () {
                                lookup.val($(this).val());
                                $(item).val(creatFromInput.val());
                                lookup.trigger("label.changeLabel");
                                lookup.trigger("extend.changetext");
                                console.log($(item), lookup);
                                $.fn.xmsSelecteDown.setLookUpState(lookup);
                            }).on('lookup.clear', function () {
                                var inputid = lookup.attr('id');
                                var valueid = inputid.replace(/_text$/, "");
                                $('#' + inputid).val('').trigger('change');
                                $('#' + valueid).val('').trigger('change');
                                if ($('#' + inputid).siblings(".xms-dropdownLink").length > 0) {
                                    $('#' + inputid).siblings(".xms-dropdownLink").remove();
                                }
                            });
                            lookup.val(_record[itemId + 'name']);
                            //console.log("_record[itemId + 'name']", _record[itemId + 'name'])
                            $.fn.xmsSelecteDown.setLookUpState(lookup);
                        } else {
                            bussinessInput.on('keyup', function () {
                                creatFromInput.val($(this).val());
                                creatFromInput.trigger('change');
                            });
                            creatFromInput.on('keyup', function () {
                                bussinessInput.val($(this).val());
                            });
                            //console.log(datatype);
                            if (datatype == "datetime") {
                                var _val = _record[itemId];
                                var inserVal = '';

                                if (_format) {
                                    if (_format == "yyyy/MM/dd") {
                                        if (_val != null) {
                                            if (document.all) {
                                                _val = _val.replace(/\-/, '\/');
                                            }
                                            console.log('bs-_format', _format, _val)
                                            _val = new Date(_val).format('yyyy-MM-dd');
                                            bussinessInput.val(_val);
                                        }
                                    }
                                }
                                bussinessInput.on('change', function () {
                                    creatFromInput.val($(this).val());
                                    creatFromInput.trigger('change');
                                });
                                creatFromInput.on('change', function () {
                                    bussinessInput.val($(this).val());
                                });
                            }
                            if (datatype == 'picklist') {
                                $(item).on('bindinput.complete', function () {
                                    var $target = $(item).next();
                                    dirtyChecker.bindCheckerEvent([{ key: this.id, value: this.value }]);
                                    $target.on('change', function () {
                                        $target.val($(this).val());
                                        $target.attr("data-value", $(this).val());
                                        $target.trigger('change');
                                    });
                                })

                            }
                        }

                    } else {

                        var lookup = $(item).prev().find('input.lookup ');
                        if (lookup.length > 0) {
                            datatype = datatype ? datatype : $(item).prev().find('input.lookup ').attr('data-attributetype');
                        }

                        if (datatype == "lookup" || datatype == "customer" || datatype == "owner") {
                            var lookup = $(item).prev().find('input.lookup ');
                            lookup.val(_record[itemId + "name"]);
                            $(item).val(_record[itemId])
                            $.fn.xmsSelecteDown.setLookUpState(lookup);
                        } else if (datatype == "picklist") {
                            //console.log($(item), _record[itemId]);
                            $(item).val(_record[itemId]);
                        } else {
                            //console.log('2222222222222222222222', $(item), _record[itemId])
                            if (_record[itemId] && _record[itemId] != "") {
                                bussinessInput.val(_record[itemId])
                            }
                        }
                    }
                });
            });
        }
        , showInErrorMsg: function ($input, msg) {
            var msgbox = null;
            $input.parent().css('position', "relative");
            if ($input.data().msgbox && $input.data().msgbox.length > 0) {
                msgbox = $input.data().msgbox;
                msgbox.show();
            } else {
                msgbox = $('<div class="inputErrorMsgBox"><em class="glyphicon glyphicon-exclamation-sign"></em><span class="inputErrorMsg"></span></div>');
                msgbox.appendTo($input.parent());
                $input.data().msgbox = msgbox
            }
            var bound = {
                x: $input.position().left,
                y: $input.position().top,
                w: $input.outerWidth(),
                h: $input.outerHeight()
            }
            msgbox.find('.inputErrorMsg').text(msg);
            msgbox.css({ "top": bound.y - bound.h, "left": bound.x });
        }
        , hideInErrorMsg: function ($input) {
            if ($input.length > 0) {
                msgbox = $('.inputErrorMsgBox');
                msgbox.hide();
            }
        }
        , checkFormRequire: function () {
            var formWrap = $('.tab-pane.active'), flag = true;
            var currentIndex = formWrap.index();
            console.log('currentIndex', currentIndex);
            var checkwrap = $('.tab-pane:lt(' + currentIndex + ')');
            var $input = null;
            formWrap.each(function (ii, nn) {
                var rflag = true;
                var $requires = $('input.required:not(:disabled),textarea.required:not(:disabled)', nn);
                $requires.each(function (key, item) {
                    var $_this = $(item);
                    var val = $_this.val();
                    console.log(item.id);
                    if (val == "") {
                        rflag = false;
                        $input = $_this;
                        return false;
                    }
                });
                if (rflag == false) {
                    flag = false;
                    return false;
                }
            });
            if (!flag) {
                BusinessProcessModel.hideInErrorMsg($input);
                BusinessProcessModel.showInErrorMsg($input, '必填项不能为空');
                $input.off('change.checkreq').on('change.checkreq', function () {
                    BusinessProcessModel.hideInErrorMsg($input);
                });
            }
            return flag;
        }
        , getDdlItems: function (optionsetid, callback) {
            Xms.Web.PageCache('business', ORG_SERVERURL + '/api/schema/optionset/getitems/' + optionsetid, { type: optionsetid, data: null }, function (res) {
                // console.log('res', res);
                callback && callback(res.Content != '' ? JSON.parse(res.Content) : []);
            });
        }
        , loadAttributeInputType: function () {
            var formWrap = $('.tab-pane', "#businessprocess-section");
            var $inputs = formWrap.find('input');
            var EntityId = Xms.Page.PageContext.EntityId;
            $inputs.each(function (key, item) {
                var $item = $(item);
                var datatype = $item.attr('data-attributetype');
                var $id = this.id;
                var $name = this.name;
                var attributeid = $item.attr('data-attributeid');
                var ddlitems = [];
                var attributename = $item.attr('data-attributename');
                var optionsetid = $item.attr('data-optionsetid');
                if (typeof dirtyChecker !== "undefined") {
                    console.log('addwatch', $id);
                    dirtyChecker.addWatch($id, _record[$id] || "");
                }
                if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {
                    BusinessProcessModel.bindInput(attributename, $(this), datatype, attributeid, EntityId, ddlitems, optionsetid);
                } else if (datatype == 'picklist') {
                    BusinessProcessModel.bindInput(attributename, $(this), datatype, attributeid, EntityId, ddlitems, optionsetid);
                } else {
                    BusinessProcessModel.bindInput(attributename, $(this), datatype, attributeid, EntityId, ddlitems, optionsetid);
                }
               // bindCheckerEvent([{key:$id,value:(_record[$id] || "")}])
            });
        }
        , bindInput: function (attributename, input, datatype, attributeid, EntityId, ddlitems, optionsetid) {
            //   console.log('bindInput', datatype, attributeid)
            if (datatype == "datetime") {
                var format = $(input).attr('data-format') || 'yyyy-MM-dd HH:mm:ss';
               // console.log($(input));
                var tempformat = format;
                format = format.replace("yyyy", "Y").replace("dd", "d").replace("hh", "h").replace("mm", "i").replace('MM', "m").replace('ss', "s").replace('HH', "H").replace('h', "H");
                if (tempformat.indexOf("hh:mm") > -1) {
                    $(input).datetimepicker({
                        step: 15
                        , format: format
                    })
                } else {
                    $(input).datetimepicker({
                        timepicker: false
                        , format: format
                    })
                }
            } else if (datatype == "picklist") {
                var self = $(input);
                BusinessProcessModel.getDdlItems(optionsetid, function (res) {
                    var isselect = self.val() == "" ? false : true;
                    //console.log(self.val())
                    self.picklist({
                        required: self.is('.required'),
                        items: res
                        , displaytype: self.is('.bit') ? 'radio' : 'select'
                        , isDefault: isselect
                    });
                    self.trigger('bindinput.complete');
                });

            } else if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {
                var self = $(input);
                var inputid = self.prop('id');
                var valueid = inputid.replace(/_text$/, '');
                console.log(valueid)
                var value = self.val();
                var lookupurl = ORG_SERVERURL + '/entity/RecordsDialog?singlemode=true&sortby=CreatedOn&inputid=' + inputid;
                //tempobj["FilterOperator"] = 1;
                if (self.attr('data-defaultviewid') && self.attr('data-defaultviewid') != '') {
                    lookupurl += '&queryid=' + self.attr('data-defaultviewid');
                }
                else {
                    lookupurl += '&entityid=' + self.attr('data-lookup');
                }
                var disabled = self.prop("disabled");
                var lookupid = self.attr('data-lookup');
                defaultLookupUrl = lookupurl;

                //getvalue
                if (value && value != '') {
                    //syncCount++;
                    hasValueList.push(inputid);
                    getRecordInfo(valueid, function (response) {
                        console.log('readonlylookup', self);
                        if (self.attr('data-onlylabel') && self.attr('data-onlylabel') == 'true') {
                            self.next().remove();
                            self.replaceWith('<a href="' + ORG_SERVERURL + '/entity/edit?entityid=' + lookupid + '&recordid=' + value + '" target="_blank"><span name="' + self.prop('name') + '" id="' + self.prop('id') + '">' + response.content.name + '</span></a>');
                        }
                        else {
                            var attr = Xms.Page.getAttribute(self.prop('name').replace(/_text/, ''));
                            attr.setValue({ id: response[valueid.toLowerCase()], name: response[valueid.toLowerCase() + "name"] });
                            self.lookup({
                                disabled: disabled,
                                btnDisabled: disabled,
                                dialog: function (obj, callback) {
                                    var f = $('#' + obj.prop('id').replace(/_text/, '')).attr("data-filter");
                                    if (f) f = JSON.parse(decodeURIComponent(f));
                                    else f = null;
                                    var inputDom = $("#" + inputid);
                                    var valueDom = $("#" + valueid);
                                    var dependName = inputDom.attr('data-dependentattributename');
                                    if (typeof dependName === "string" && dependName != "") {
                                        lookupurl = defaultLookupUrl;
                                        var TargetDom = $("#" + dependName);
                                        var targetName = TargetDom.attr("data-sourcename");//打开搜索框前 增加过滤条件
                                        lookupurl += '&dependentattributename=' + inputDom.attr('data-dependentattributename') + '&RelationshipName=' + inputDom.attr("data-filterrelationshipname") + '&ReferencedRecordId=' + (TargetDom.val() || "");
                                    }
                                    if (f) {
                                        Xms.Web.OpenDialog(lookupurl, 'selectRecordCallback', { filter: f }, function () { callback && callback(); });
                                    } else {
                                        Xms.Web.OpenDialog(lookupurl, 'selectRecordCallback', null, function () { callback && callback(); });
                                    }
                                }
                                , clear: function () {
                                    $('#' + inputid).val('').trigger('change');
                                    $('#' + valueid).val('').trigger('change');
                                    console.log('inputid', inputid);
                                    if ($('#' + inputid).siblings(".xms-dropdownLink").length > 0) {
                                        $('#' + inputid).siblings(".xms-dropdownLink").remove();
                                    }

                                },
                                isDefaultSearch: true
                                , isShowSearch: true,
                                searchOpts: {
                                    id: lookupid
                                    , addHandler: function (tar, obj, par) {

                                        $(par.obj).trigger("lookup.triggerChange");

                                    }
                                    , delHandler: function (input) {
                                        var tarid = input.attr("id").replace("_text", "");
                                        var tarDom = $("#" + tarid);
                                        var tagContext = $('div[data-sourceattributename="' + tarid + '"]');
                                        tagContext.html('');
                                    }

                                }

                            });
                        }

                    });
                    //  });
                }
                else {

                    var attr = Xms.Page.getAttribute(name);
                    if (self.attr('data-controltype') == 'owner' || name == 'createdby' || name == 'modifiedby') {
                        if (getPageType() == "new") {
                            attr.setValue({ id: CURRENT_USER.systemuserid, name: CURRENT_USER.username });
                        }
                    }
                    if (name == 'createdby' || name == 'modifiedby' || name == 'organizationid' || name == 'owningbusinessunit' || name == 'owneridtype' || name == 'versionnumber') {
                        self.prop('disabled', true);
                    }
                    else {
                        self.lookup({
                            disabled: disabled,
                            btnDisabled: disabled,
                            dialog: function (obj, callback) {
                                var f = $('#' + obj.prop('id').replace(/_text/, '')).attr("data-filter");
                                if (f) f = JSON.parse(decodeURIComponent(f));
                                else f = null;

                                var inputDom = $("#" + inputid);

                                Xms.Web.OpenDialog(lookupurl, 'selectRecordCallback', { filter: f }, function () { callback && callback(); });
                            }
                            , clear: function () {
                                $('#' + inputid).val('').trigger('change');
                                console.log('inputid', $('#' + inputid).siblings(".xms-dropdownLink"));
                                if ($('#' + inputid).siblings(".xms-dropdownLink").length > 0) {
                                    $('#' + inputid).siblings(".xms-dropdownLink").remove();
                                }
                                var valueid = inputid.replace(/_text/, '');
                                $('#' + valueid).val('').trigger('change');

                            },
                            isDefaultSearch: true
                            , isShowSearch: true
                            , searchOpts: {
                                id: lookupid,
                                addHandler: function (tar, obj, par) {

                                    $(par.obj).trigger("lookup.triggerChange");
                                }, delHandler: function (input) {
                                    var tarid = input.attr("id").replace("_text", "");
                                    var tarDom = $("#" + tarid);
                                    var tagContext = $('div[data-sourceattributename="' + tarid + '"]');
                                    tagContext.html('');
                                }

                            }

                        });

                    }
                }
            }

            //
            //$('.detail-table').each(function () {
            //    var intems = $('.bpattr-item-panel',this);
            //    var $this = $(this), _count = $this.attr('data-count');
            //    if (_count && _count % 2==0 && _count%3!=0) {
            //        intems.removeClass('col-sm-4').addClass('col-sm-6');
            //    }
            //});
        }
        //下一阶段，向上切换按钮，显示两个，和显示一个的情况
        , updatePrevNextClass: function () {
            var $stageItem = $('.process .stage-item');
            var onlyShowPrevClass = function () {
                $stageItem
                  .removeClass('stage-item-prev-next')
                  .removeClass('stage-item-next')
                  .addClass('stage-item-prev');
            };

            var onlyShowNextClass = function () {
                $stageItem
                  .removeClass('stage-item-prev-next')
                  .removeClass('stage-item-prev')
                  .addClass('stage-item-next');
            };

            var showPrevNextClass = function () {
                $stageItem
                  .addClass('stage-item-prev-next');
            };
        }
        , CreateRecord: function (entityid, relationshipname) {
            var url = ORG_SERVERURL + '/entity/create?entityid=' + entityid + '&relationshipname=' + relationshipname + '&referencedrecordid=' + Xms.Page.PageContext.RecordId + '&businessflowinstanceid=' + BusinessProcessModel.InstanceId;
            //Xms.Web.OpenWindow(url);
            $('#createModal').modal({
                keyboard: true
            });
            $('#createModal').find('.modal-body').html('<iframe src="' + url + '" frameborder="0" width="100%" height="500"></iframe>');
            //$('#createModal').find('.modal-content').css('width',$(document).width()/2).css('height',$(document).height()/1.5);
            $('#createModal').find('.modal-title').html('<span class="glyphicon glyphicon-file"></span> ' + ' - ' + LOC_NEWRECORD);
        }
        , updateRecord: function (callback) {
            var obj = { entityid: Xms.Page.PageContext.EntityId, data: {} };
            obj.data.id = Xms.Page.PageContext.RecordId;
            obj.name = Xms.Page.PageContext.EntityName;
            var formWrap = $('.tab-pane', "#businessprocess-section");
            var $inputs = formWrap.find('input:not(:disabled),textarea.bp_input:not(:disabled)');
            var EntityId = Xms.Page.PageContext.EntityId;
            var hasChanged = false;
            $inputs.each(function (key, item) {
                var $this = $(this);
                var $name = this.name;
                var $id = this.id;
                var datatype = $this.attr('data-attributetype');
                var value = $this.val();
                if (datatype == "lookup" || datatype == "owner" || datatype == "customer") {
                    $value = $('input[name="' + $name.replace('_text', '') + '"]', formWrap);
                    $name = $value.attr('name');
                    value = $value.val();
                }
                console.log($name);
                if ($name.indexOf('bp_') > -1) {
                    $name = $name.replace(/^bp_/g, '');
                }
                obj.data[$name] = value;
                hasChanged = true;
            });
            if (!hasChanged) {
                callback && callback();
                return;
            }
            obj.data = JSON.stringify(obj.data);
            Xms.Web.Post('/api/data/update', obj, false, function (response) {
               // Xms.Web.Toptip(response.content);
                if (response.IsSuccess) {
                   // return false;
                    callback && callback();
                }
            });
        }
        , UpdateStage: function (entityid, recordid, stageid, callback) {
            console.log('UpdateStage', entityid, recordid, stageid);
            BusinessProcessModel.updateRecord(function () {

                var postData = { entityid: entityid || Xms.Page.PageContext.EntityId, recordid: recordid || Xms.Page.PageContext.RecordId, workflowid: BusinessProcessModel.WorkFlowId, stageid: stageid, fromrecordid: Xms.Page.PageContext.RecordId, instanceid: BusinessProcessModel.InstanceId };
                Xms.Web.Post(ORG_SERVERURL + '/api/flow/UpdateProcessStage', postData, false, function (response) {
                    if (response.IsSuccess) {
                        callback && callback(response);
                    }
                    else {
                        Xms.Web.Toast(response.Content, false);
                    }
                }, null, null, false);

            });
        },
        retrieveById: function (callback) {
            var url = '/api/data/retrieve/' + Xms.Page.PageContext.EntityName + '/' + Xms.Page.PageContext.RecordId;
            Xms.Web.Get(url, function (res) {
                callback && callback(res);
                console.log(res);
            });
        },
        createRecord: function (entityid, relationshipname, referencedrecordid) {
            var url = ORG_SERVERURL + '/entity/create?entityid=' + GridViewModel.entityid + '&relationshipname=' + GridViewModel.relationshipname + '&referencedrecordid=' + GridViewModel.referencedrecordid + '&grid=' + GridViewModel.gridid + '&businessflowinstanceid=' + Xms.Page.PageContext.BusinessFlowInstanceId;
            //Xms.Web.OpenWindow(url);
            $('#createModal').modal({
                keyboard: true
            });
            $('#createModal').find('.modal-body').html('<iframe src="' + url + '" frameborder="0" width="100%" height="500"></iframe>');
            //$('#createModal').find('.modal-content').css('width',$(document).width()/2).css('height',$(document).height()/1.5);
            $('#createModal').find('.modal-title').html('<span class="glyphicon glyphicon-file"></span> ' + GridViewModel.entityloclaizedname + ' - ' + LOC_NEWRECORD);
        }
    };
    $(function () {

        //

        //鼠标移到图标，显示‘商机销售流程’
        $('.process').on('mouseenter', '.info-wrapper', function () {
            $('.proces-text').css('visibility', 'visible');
        })
        .on('mouseleave', '.info-wrapper', function () {
            $('.proces-text').css('visibility', 'hidden');
        })
        //点击收起
        .on('click', '.container-button', function () {
            var $this = $(this);
            var $tabcontent = $('.tab-content','#businessprocess-section');
            if ($tabcontent.data('status') === false) {
                $this.html('<i class="icon-collapsible"></i>').data('status', true);
                $tabcontent.parent().removeClass('slide-up');
                $tabcontent.stop().slidedown();
            } else {
                $this.html('<i class="icon-collapsible"></i>').data('status', false);
                $tabcontent.parent().addClass('slide-up');
            }
            $tabcontent.stop().slideToggle();
        })
        .on('click', '.stage-item', function () {
            var isloadNewData = false;
            var $this = $(this);

            if (!BusinessProcessModel.checkFormRequire()) {
                //Xms.Web.Alert(false, '必填项不能为空');
                return false;
            }

            var $tabcontentWrap = $('.tab-content-wrap');
            if ($tabcontentWrap.hasClass('slide-up')) {
                $tabcontentWrap.removeClass('slide-up');
                $tabcontentWrap.find('.tab-content').show();
            }
            var stageNum = $('.process').attr('data-count');
            var $navTabs = $this.closest('.nav-tabs');
            var $activeLi = $this;
            //console.log($activeLi);
            var $flagStage = $navTabs.find('li.flag');
            var flagIndex = $flagStage.index();
            var activeIndex = $this.index();
            var lileng = $('li.stage-item').length;
            //console.log(activeIndex, flagIndex)
            if (activeIndex < flagIndex) {
                var prevEntityid = $activeLi.attr('data-entityid');
                if (prevEntityid != Xms.Page.PageContext.EntityId) {
                    var reAttributeName = $activeLi.attr('data-relateattributename');
                    var referencedrecordid = $flagStage.attr('data-recordid');
                    var preventityname = $activeLi.attr('data-entityname');
                    var preventityid = $activeLi.attr('data-entityid');
                    var relationshipname = $activeLi.attr('data-relationshipname');
                    var curentityid = $flagStage.attr('data-entityid');
                    var prevrecordid = $activeLi.attr('data-recordid');

                    // return false;
                    if (prevEntityid != Xms.Page.PageContext.EntityId) {//检查如果为关联实体
                        location.href = ORG_SERVERURL + "/entity/create?entityid=" + preventityid + "&recordid=" + prevrecordid + '&businessflowinstanceid=' + BusinessProcessModel.InstanceId;
                    } else {//如果上一个的实体与当前一样
                        Xms.Web.LoadPage(ORG_SERVERURL + '/flow/businessprocess', { entityid: Xms.Page.PageContext.EntityId, recordid: prevrecordid || Xms.Page.PageContext.RecordId }, function (data) {
                            if (data.indexOf('{') == 0) {
                                var d = JSON.parse(data);
                                console.log(d);
                                if (d.StatusName == 'error')
                                    return;
                            }
                            var $buss = $('#businessprocess-section');
                            setTimeout(function () {
                                $buss.html(data);
                            });
                        });
                        return false;
                    }
                }
            } else if (activeIndex == flagIndex) {
                var prevEntityid = $activeLi.attr('data-entityid');
                if (prevEntityid != Xms.Page.PageContext.EntityId) {
                    var reAttributeName = $activeLi.attr('data-relateattributename');
                    var referencedrecordid = $flagStage.attr('data-recordid');
                    var preventityname = $activeLi.attr('data-entityname');
                    var preventityid = $activeLi.attr('data-entityid');
                    var relationshipname = $activeLi.attr('data-relationshipname');
                    var curentityid = $flagStage.attr('data-entityid');
                    var prevrecordid = $activeLi.attr('data-recordid');
                    location.href = ORG_SERVERURL + "/entity/create?entityid=" + preventityid + "&recordid=" + prevrecordid + '&businessflowinstanceid=' + BusinessProcessModel.InstanceId;
                }
            }

        })
        //点击向上，向下按钮，切换tab
        .on('click', '.prev-stage, .next-stage', function () {
            if (!BusinessProcessModel.checkFormRequire()) {
                // Xms.Web.Alert(false, '必填项不能为空');
                 return false;
            };
            var $this = $(this);
            var stageNum = $('.process').attr('data-count');
            var $navTabs = $this.closest('.nav-tabs');
            var $activeLi = $navTabs.find('li.active');
            var $flagStage = $navTabs.find('li.flag');
            var index = $flagStage.index();
            var lileng = $('li.stage-item').length;
            if ($flagStage.hasClass('flag')) {
                if ($this.hasClass('prev-stage')) {//如果点击上一步

                    var $prevStage = $flagStage.prev('.stage-item');
                    if ($prevStage.length > 0) {//如果前面还有阶段
                        var prevEntityid = $prevStage.attr('data-entityid');
                        var reAttributeName = $prevStage.attr('data-relateattributename');
                        var referencedrecordid = $flagStage.attr('data-recordid');
                        var preventityname = $prevStage.attr('data-entityname');
                        var preventityid = $prevStage.attr('data-entityid');
                        var relationshipname = $prevStage.attr('data-relationshipname');
                        var curentityid = $flagStage.attr('data-entityid');
                        var prevrecordid = $prevStage.attr('data-recordid');

                        //获取相关记录
                        BusinessProcessModel.UpdateStage(preventityid, prevrecordid, $prevStage.attr('data-stageid'), function (res) {
                            if (prevEntityid != $flagStage.attr('data-entityid')) {//检查如果为关联实体
                                location.href = ORG_SERVERURL + "/entity/create?entityid=" + preventityid + "&recordid=" + prevrecordid + '&businessflowinstanceid=' + BusinessProcessModel.InstanceId;
                            } else {//如果上一个的实体与当前一样
                                Xms.Web.LoadPage(ORG_SERVERURL + '/flow/businessprocess', { entityid: Xms.Page.PageContext.EntityId, recordid: Xms.Page.PageContext.RecordId }, function (data) {
                                    if (data.indexOf('{') == 0) {
                                        var d = JSON.parse(data);
                                        //console.log(d);
                                        if (d.StatusName == 'error')
                                            return;
                                    }
                                    var $buss = $('#businessprocess-section');
                                    setTimeout(function () {
                                        $buss.html(data);
                                    });
                                });
                                return false;
                            }
                        });
                        return false;

                    } else {//如果是第一个阶段的时候

                    }

                    if (index - 1 == 0) {
                        $this.hide();
                    }
                    if (index < stageNum) {
                        $this.parent().find('.next-stage').show();
                    }
                    --index;
                    if (index < 0) index = 0;

                } else if ($this.hasClass('next-stage')) {//如果点击下一步

                    var $nextStage = $flagStage.next('.stage-item');
                    if ($nextStage.length > 0) {//如果后面还有阶段
                       // console.log($nextStage);
                        var nextEntityid = $nextStage.attr('data-entityid');
                       // console.log(nextEntityid);
                        if (nextEntityid != $flagStage.attr('data-entityid')) {//检查如果为关联实体
                            $('.stage-new-item').show();
                            $('.stage-new-header').text($nextStage.attr('data-referencingentitylocalizedname'));
                            var $recordlist = $('#stage-list');
                            $recordlist.empty();
                            var creatNewStageRec = $('#creatNewStageRec');
                            var reAttributeName = $nextStage.attr('data-relateattributename');
                            var referencedrecordid = $flagStage.attr('data-recordid');
                            var entityname = $nextStage.attr('data-entityname');
                            var nextentityid = $nextStage.attr('data-entityid');
                            var relationshipname = $nextStage.attr('data-relationshipname');
                            var curentityid = $flagStage.attr('data-entityid');

                            //获取相关记录
                            var filter = { "Conditions": [{ "AttributeName": reAttributeName, "Operator": 0, "Values": [referencedrecordid] }] };
                            var queryObj = { entityname: entityname, Criteria: filter, ColumnSet: { allcolumns: true } };
                            var pageinfo = { Count: 5, PageNumber: 1, PageSize: 5 };
                            queryObj.pageinfo = pageinfo;
                            var data = JSON.stringify({ "query": queryObj });
                            creatNewStageRec.attr('data-href', ORG_SERVERURL + '/api/flow/ForwardAndAppend?entityid=' + nextentityid + '&relationshipname=' + relationshipname + '&referencedrecordid=' + referencedrecordid + '&stageid=' + $nextStage.attr('data-stageid') + '&workflowid=' + BusinessProcessModel.WorkFlowId + '&instanceid=' + BusinessProcessModel.InstanceId)
                            .off('click').on('click', function () {
                                var href = $(this).attr('data-href');
                                BusinessProcessModel.updateRecord(function () {
                                    //location.href = href;
                                    Xms.Web.Get(href, function (response) {
                                        console.log('abc=', response);
                                        if (response.IsSuccess) {
                                            var redirectUrl = ORG_SERVERURL + '/entity/create?';
                                            var args = [];
                                            for (var i in response.content) {
                                                args.push(i + "=" + response.content[i]);
                                            }
                                            location.href = redirectUrl + args.join('&');
                                        }
                                    })
                                });
                            });
                            Xms.Web.GetJson('/api/data/Retrieve/Multiple', data, function (response) {
                                if (response.content) {

                                    var resDatas = response.content;
                                    console.log($.isArray(resDatas), response.content.items, $.isArray(response.content.items));
                                    if (!$.isArray(resDatas) && response.content.items && $.isArray(response.content.items)) {

                                        resDatas = response.content.items;
                                    }
                                    var _html = [];
                                    var dataLength = resDatas.length;//回传的数据的个数;

                                    $.each(resDatas, function (key, item) {

                                        var itemrecordid = item[entityname.toLowerCase() + 'id'];
                                        console.log(entityname.toLowerCase() + 'id', item, itemrecordid);
                                        _html.push('<li><a target="_blank" href="' + ORG_SERVERURL + '/entity/create?entityid=' + nextentityid + '&recordid=' + itemrecordid + '&businessflowinstanceid=' + BusinessProcessModel.InstanceId + '"><span class="glyphicon glyphicon-share-alt"></span></a><span class="stage-record" data-recordid="' + itemrecordid + '">' + (item.name || '&nbsp;&nbsp;&nbsp;&nbsp;') + '</span></li>');
                                    });
                                    $('#stage-list').html(_html.join(''));
                                    $('.stage-list-count').text(dataLength);
                                    $('#stage-list').find('.stage-record').off('click').on('click', function (e) {
                                        var _recoredid = $(this).attr('data-recordid');
                                        $nextStage.attr('data-recordid', _recoredid);
                                        console.log(nextEntityid);
                                        BusinessProcessModel.UpdateStage(nextentityid, $nextStage.attr('data-recordid'), $nextStage.attr('data-stageid'), function (res) {
                                            location.href = ORG_SERVERURL + "/entity/create?entityid=" + nextentityid + "&recordid=" + _recoredid;
                                        });
                                    });
                                }
                            }, null, null, 'post');
                            return false;
                        } else {//如果下一个的实体与当前一样
                           // console.log('如果下一个的实体与当前一样',nextEntityid);
                            BusinessProcessModel.UpdateStage(nextEntityid, $nextStage.attr('data-recordid'), $nextStage.attr('data-stageid'), function (res) {

                                Xms.Web.LoadPage('/flow/businessprocess', { entityid: Xms.Page.PageContext.EntityId, recordid: Xms.Page.PageContext.RecordId }, function (data) {
                                    if (data.indexOf('{') == 0) {
                                        var d = JSON.parse(data);
                                        console.log(d);
                                        if (d.StatusName == 'error')
                                            return;
                                    }
                                    var $buss = $('#businessprocess-section');
                                    setTimeout(function () {
                                        $buss.html(data);
                                    });
                                });
                            });
                            return false;
                        }
                    } else {//如果跳到最后一个阶段的时候

                    }
                    var $stageItem = $('.process .stage-item');
                    if (index == stageNum - 2) {
                        $this.hide();
                    }
                    if (index == 0) {
                        $this.parent().find('.prev-stage').show().addClass('act');
                    }
                    ++index;
                    if (index > lileng - 1) index = lileng - 1;

                }
                $activeLi.removeClass('flag');
                $navTabs.find('li:eq(' + index + ') a').tab('show').closest('li').addClass('flag');
                //BusinessProcessModel.updatePrevNextClass();
                $navTabs.find('li.active').attr('data-isedited', true);
                //BusinessProcessModel.UpdateStage($navTabs.find('li.active').attr('data-entityid'), $navTabs.find('li.active').attr('data-recordid'), $navTabs.find('li.active').attr('data-stageid'));
            }
            //  loadAttributeInputType()
        });
        function closeWin(e) {
            e = e || window.event;
            var target = e.target || e.srcElement;
            var $this = $(this);
            if ($(target).closest('#nextStageBtn').length == 0) {
                $('.stage-new-item').hide();
            }
        }
        $(document).off('click', closeWin);
        $(document).on('click', closeWin);
        BusinessProcessModel.setInitIdAndName();//必须先执行，检查ID和NAME是否已存在下面的表单中;
        BusinessProcessModel.loadAttributeInputType();
        BusinessProcessModel.initFormSetData();
        $('.process .stage-item').each(function (i, n) {
            if ($(n).attr('data-entityid') != BusinessProcessModel.EntityId) {
                $(n).addClass('locked');
                $(n).find('a').prepend('<span class="glyphicon glyphicon-lock"></span>');
            }
        });

        //给已完成的加上勾
        $('#businessprocess-section .stage-item[data-entityid="' + Xms.Page.PageContext.EntityId + '"]:not(".flag")').each(function () {
            var flagStage = $('li.stage-item.flag');
            var flagIndex = flagStage.index();
            var thisIndex = $(this).index();
            if (thisIndex < flagIndex) {
                $(this).addClass('success-stage');
            }
        });
    });
</script>